package unique;

//import backup.*;
import java.awt.HeadlessException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

public class GUIServer extends javax.swing.JPanel {

    private DefaultListModel listModel;
    private Hashtable<String, WebServer> servidores;

    /**
     * Creates new form GUIServer
     */
    public GUIServer() {
        servidores = new Hashtable<String, WebServer>();

        listModel = new DefaultListModel();
        //listModel.addElement("teste");
        initComponents();
    }

    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("Servidor"); //pode editar aqui pra algo legal
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new GUIServer();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI();
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        guiArquivo = new javax.swing.JTextField();
        guiPorta = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        guiEncerrar = new javax.swing.JButton();
        guiIniciar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        guiServerList = new JList(listModel);

        jLabel1.setText("Iniciar novo servidor");

        jLabel2.setText("Porta:");

        jLabel3.setText("Arquivo:");

        jLabel4.setText("Servidores executando");

        guiEncerrar.setText("Encerrar");
        guiEncerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guiEncerrarActionPerformed(evt);
            }
        });

        guiIniciar.setText("Iniciar");
        guiIniciar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guiIniciarActionPerformed(evt);
            }
        });

        guiServerList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        guiServerList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                guiServerListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(guiServerList);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel1)
                    .addComponent(guiEncerrar)
                    .addComponent(guiIniciar)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(guiPorta, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(guiArquivo, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(guiPorta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(guiArquivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(guiIniciar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(guiEncerrar)
                .addGap(6, 6, 6))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void guiServerListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_guiServerListValueChanged
        // TODO add your handling code here:

    }//GEN-LAST:event_guiServerListValueChanged

    private void guiIniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guiIniciarActionPerformed
        // TODO add your handling code here:
        boolean erro = false;
        if (guiPorta.getText().length() == 0) {
            JOptionPane.showMessageDialog(null, "Por favor, coloque uma porta válida.");
            erro = true;
        }
        if (guiArquivo.getText().length() == 0) {
            JOptionPane.showMessageDialog(null, "Por favor, coloque um arquivo válido.");
            erro = true;
        }

        try {
            if (Integer.parseInt(guiPorta.getText()) < 2000) {
                JOptionPane.showMessageDialog(null, "A porta deve ser um número maior que 2000");
                erro = true;
            }
        } catch (NumberFormatException | HeadlessException e) {
            JOptionPane.showMessageDialog(null, "A porta deve ser um número maior que 2000");
            erro = true;
        }
        
        if(servidores.containsKey(guiPorta.getText())){
            JOptionPane.showMessageDialog(null, "Já existe um servidor nessa porta");
        }
        
        if(!erro){
            int porta = Integer.parseInt(guiPorta.getText());
            String portaS = guiPorta.getText();
            String arquivo = guiArquivo.getText();
            arquivo += ".txt";
            guiPorta.setText(null);
            guiArquivo.setText(null);
            //System.out.println("porta: " + porta + "arquivo: " + arquivo);
            
            WebServer newServer = null;
            try {
                newServer = new WebServer(porta, arquivo);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "Não foi possível criar o servidor");
                erro = true;
            }
            if(!erro){
            servidores.put(portaS, newServer);
            servidores.get(portaS).start();
                //System.out.println("aehoo");
            listModel.addElement(portaS);
        }}
    }//GEN-LAST:event_guiIniciarActionPerformed

    private void guiEncerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guiEncerrarActionPerformed
        // TODO add your handling code here:
        boolean erro = false;
        
        if(guiServerList.getSelectedValue() == null)
            erro = true;
        
        if(!erro){
            String servidor = listModel.getElementAt(guiServerList.getSelectedIndex()).toString();
            //servidores.get(servidor).stop();
            servidores.get(servidor).setFechaServidor(false);
            servidores.remove(servidor).setFechaServidor(false);
            //servidores.remove(servidor);
            listModel.remove(guiServerList.getSelectedIndex());
            //System.out.println(servidor);
        }
    }//GEN-LAST:event_guiEncerrarActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField guiArquivo;
    private javax.swing.JButton guiEncerrar;
    private javax.swing.JButton guiIniciar;
    private javax.swing.JTextField guiPorta;
    private javax.swing.JList guiServerList;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
